<template>
    <view class="">
        <view class="status_bar" :style="{'background-color': bindStatus?backColor:'#999'}">
            <!-- 这里是状态栏 -->
        </view>
        <view class="body">
            <view class="top_block" :style="{'padding-top':top+'rpx','background-color':bindStatus?backColor:'#999',}">
                <!-- 导航栏 -->
                <view class="navbar_wrap">
                    <view class="navbar">
                        <view class="left" @tap="navTo('back')">
                            <image src="@/static/icon/p_036.png" mode="heightFix" class="arrow-right">
                            </image>
                        </view>
                        <view class="title">
                            设备管理
                        </view>
                        <view class="right"></view>
                    </view>
                </view>

                <view class="isAction flex-center-center">
                    <view class="actionLeft">
                        <image src="@/static/icon/p_037.png" mode="heightFix" class="img"></image>
                    </view>
                    <view class="actionCenter">
                        <blockquote v-if="bindStatus">
                            <p> 设备型号：{{dataFile.modelName}}</p>
                            <p>设备/卡编号：{{dataFile.snCode}}</p>
                        </blockquote>
                        <blockquote v-else>
                            <p>未识别到设备</p>
                        </blockquote>


                    </view>
                    <view class="actionRight">
                        <blockquote v-if="bindStatus">
                            <image src="@/static/icon/p_038.png" mode="heightFix" class="img"></image>
                        </blockquote>
                        <blockquote v-else>
                            <view class="actionRight-icon">
                                <text class="look">点此查看</text>
                                <u-icon size="20" color="#fff" name="error-circle"></u-icon>
                            </view>

                        </blockquote>

                        <!--    {{wifiInfo}} -->
                    </view>
                </view>
            </view>
            <view class="wifiTitle">
                <p> WIFI名称:
                    <span v-if="bindStatus">{{dataFile.wifiName}}</span>
                    <span v-else> ---- </span>
                </p>
                <p> WIFI密码:
                    <span v-if="bindStatus"> {{dataFile.wifiPasswd}}</span>
                    <span v-else> ---- </span>
                </p>
            </view>
            <view class="network">
                <view class="title">
                    网络管理
                </view>
                <view class="contain flex-start" v-if="bindStatus">
                    <view class="justDiv flex-center-center" v-for="(item,index) in dataFile.list" :key="item.simId"
                        @click="selected(item)" :class="{'active' : active == item.simId}" style="margin-left: 20rpx;">
                        <view class="">
                            <p style="font-size: 24rpx;margin-bottom: 8rpx;">
                                <!-- {{item.state === '1'?'在用':item.state === '2'?'去实名':'离线'}} -->
                                <span v-if="item.status === 1"> 在用</span>
                                <span v-if="item.status === 2"> 离线</span>
                                <span v-if="item.status === 3"> 未实名</span>
                            </p>
                            <p>
                                <image src="/static/icon/p_012.png" mode="heightFix" class="img"
                                    v-if="item.name === '中国移动'"></image>
                                <image src="/static/icon/p_032.png" mode="heightFix" class="img"
                                    v-else-if="item.name === '中国联通'"></image>
                                <image src="/static/icon/p_031.png" mode="heightFix" class="img"
                                    v-else="item.name === '中国电信'"></image>
                                <!-- <image
                                    :src="item.name === '中国移动'?'/static/icon/p_012.png':item.name ==='中国联通'?'/static/icon/p_032.png':'/static/icon/p_031.png'"
                                    mode="heightFix" class="img"></image> -->
                            </p>
                            <p>
                                {{item.name}}
                            </p>
                        </view>
                    </view>
                </view>
            </view>
            <view class="device " :style="{'margin-top': bindStatus?'40rpx':'160rpx'}">
                <view class="title">
                    设备管理
                </view>
                <view class="contain flex-center-between" v-if="bindStatus">
                    <view class="justDiv2 flex-center-center" v-for="(item,index) in deviceList"
                        @click="deviceHandle(item)" :key="index">
                        <view class="">
                            <p>{{item.state}}</p>
                            <p>
                                <image :src="item.icon" mode="heightFix" class="img"></image>
                            </p>
                            <p>
                                {{item.name}}
                            </p>
                        </view>
                    </view>
                </view>
            </view>
            <u-modal :show="showModal" title="温馨提示" @cancel="showModal = false" showCancelButton confirmText="恢复出厂"
                @confirm="confirm">
                <view class="slot-content">
                    <text style="text-align: center;">是否恢复出厂？</text>
                </view>
            </u-modal>

            <u-modal :show="showModal1" title="温馨提示" @cancel="showModal1 = false" showCancelButton confirmText="是否关机"
                @confirm="confirm1">
                <view class="slot-content">
                    <text style="text-align: center;">是否确认关机？</text>
                </view>
            </u-modal>

            <u-modal :show="showModal2" title="温馨提示" @cancel="showModal2 = false" showCancelButton confirmText="是否重启"
                @confirm="confirm2">
                <view class="slot-content">
                    <text style="text-align: center;">是否确认重启？</text>
                </view>
            </u-modal>


            <u-popup :show="show" @close="close" model="bottom" :round="10">
                <view class="form-box">
                    <u--form labelPosition="left" :model="form" labelWidth="80" ref="uForm">
                        <u-form-item label="WIFI名称" prop="wifiName" ref="item2">
                            <u--input v-model="form.wifiName" type="text" placeholder="请设置密码(8~16位数字和字母组合)"></u--input>
                        </u-form-item>

                        <u-form-item label="WIFI密码" prop="wifiName" ref="item2">
                            <view style="width:88%;">
                                <u-input v-show="!isShowPassword" type="password" v-model="form.passWord" name=""
                                    placeholder="请设置密码(8~16位数字和字母组合)" />
                                <u-input v-show="isShowPassword" type="text" v-model="form.passWord" name=""
                                    placeholder="请设置密码(8~16位数字和字母组合)" />
                            </view>
                            <view>
                                <image v-show="!isShowPassword" src="/static/icon/p_022.png" mode="widthFix"
                                    style="width: 54rpx;vertical-align: middle;"
                                    @click="isShowPassword = !isShowPassword">
                                </image>
                                <image v-show="isShowPassword" src="/static/icon/p_030.png" mode="widthFix"
                                    style="width: 54rpx;vertical-align: middle;"
                                    @click="isShowPassword = !isShowPassword">
                                </image>
                            </view>
                        </u-form-item>


                        <u-form-item label="确认密码" prop="wifiName" ref="item2">

                            <view style="width:88%;">
                                <u-input v-show="!isShowPassword" type="password" v-model="form.againPassWord" name=""
                                    placeholder="请再次确认密码" />
                                <u-input v-show="isShowPassword" type="text" v-model="form.againPassWord" name=""
                                    placeholder="请再次确认密码" />
                            </view>
                            <view>
                                <image v-show="!isShowPassword" src="/static/icon/p_022.png" mode="widthFix"
                                    style="width: 54rpx;vertical-align: middle;"
                                    @click="isShowPassword = !isShowPassword">
                                </image>
                                <image v-show="isShowPassword" src="/static/icon/p_030.png" mode="widthFix"
                                    style="width: 54rpx;vertical-align: middle;"
                                    @click="isShowPassword = !isShowPassword">
                                </image>
                            </view>


                            <!-- <u-input v-model="form.againPassWord" v-if="isShowAgainPassword" type="text"
                                placeholder="请设置密码(8~16位数字或字母组合)">
                                <template slot="suffix">
                                    <view class="eye" @click="triggerShowAgainPassword">
                                        <image class="pass-icon"
                                            :src="isShowAgainPassword?'/static/icon/p_022.png':'/static/icon/p_030.png'"
                                            mode=""></image>
                                    </view>
                                </template>
                            </u-input>
                            <u-input v-model="form.againPassWord" v-else type="password"
                                placeholder="请设置密码(8~16位数字或字母组合)">
                                <template slot="suffix">
                                    <view class="eye" @click="triggerShowAgainPassword">
                                        <image class="pass-icon"
                                            :src="isShowAgainPassword?'/static/icon/p_022.png':'/static/icon/p_030.png'"
                                            mode=""></image>
                                    </view>

                                </template>
                            </u-input> -->
                        </u-form-item>
                    </u--form>
                    <view class="btn">
                        <u-button type="primary" shape="circle" @click="submit">确认</u-button>
                    </view>

                </view>
            </u-popup>
        </view>

        <!-- <web-view :webview-styles="webviewStyles" :src="hrefUrl" @message="getMessage"></web-view> -->

    </view>

</template>
<script>
    import {
        setDevice
    } from '@/common/api.js'
    import {
        restartDevice,
        resetDevice,
        set24G,
        set5G,
        getInfo,
        updataEsim,
    } from '@/common/newAPI.js'
    export default {
        data() {
            return {
                hrefUrl: 'https://www.runoob.com/w3cnote/flex-grammar.html',
                webviewStyles: {
                    progress: {
                        color: '#FF3333'
                    }
                },
                bindStatus: false,
                backColor: '#427af5',
                isDevice: false,
                isShowPassword: false,
                isShowAgainPassword: false,
                top: 0,
                dataFile: '',
                deviceList: [{
                        id: '1',
                        icon: require('@/static/icon/p_016.png'),
                        name: 'WIFI设置',
                    },
                    {
                        id: '2',
                        icon: require('@/static/icon/p_005.png'),
                        name: '恢复出厂',
                    }, {
                        id: '3',
                        icon: require('@/static/icon/p_013.png'),
                        name: '设备重启',
                    },
                    {
                        id: '4',
                        icon: require('@/static/icon/p_027.png'),
                        name: '设备关机',
                    },
                ],
                active: 1,
                showModal: false,
                showModal1: false,
                showModal2: false,
                snCode: "",
                form: {
                    wifiName: '',
                    passWord: '',
                    againPassWord: ''
                },
                wifiInfo: {
                    wifi24GPassword: '',
                    wifi24Ghotname: ''
                },
                show: false
            }
        },
        onLoad(options) {
            this.intoData(options)

            this.top = this.StatusBar

        },
        methods: {
            getMessage(event) {
                uni.showModal({
                    content: JSON.stringify(event.detail),
                });
            },
            close() {
                this.show = false
                // console.log('close');
            },
            intoData(options) {
                let merchantId = options.merchantId
                setDevice(merchantId).then((res) => {
                    this.dataFile = res.data
                    this.snCode = res.data.snCode
                    this.intoInfo()
                    this.form.wifiName = this.dataFile.wifiName
                    this.active = this.dataFile.list.filter(item => item.status === 1)[0].simId || '0'

                })
            },
            // 切换密码是否显示
            triggerShowPasswor() {
                this.isShowPassword = !this.isShowPassword
            },
            triggerShowAgainPassword() {
                this.isShowAgainPassword = !this.isShowAgainPassword
            },

            //判断是json还是xml
            isJSON(str) {
                if (typeof str === 'string') {
                    try {
                        var obj = JSON.parse(str)
                        if (typeof obj === 'object' && obj) {
                            return true
                        } else {
                            return false
                        }
                    } catch (e) {
                        return false
                    }
                }
            },


            //XML转JSON格式
            xmlToJson(xml) {
                let obj = {};
                if (xml.nodeType === 1) { // element node
                    if (xml.attributes.length > 0) {
                        obj["@attributes"] = {};
                        for (let j = 0; j < xml.attributes.length; j++) {
                            const attribute = xml.attributes.item(j);
                            obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
                        }
                    }
                } else if (xml.nodeType === 3) { // text node
                    obj = xml.nodeValue;
                }
                if (xml.hasChildNodes()) {
                    for (let i = 0; i < xml.childNodes.length; i++) {
                        const item = xml.childNodes.item(i);
                        const nodeName = item.nodeName;
                        if (typeof(obj[nodeName]) === "undefined") {
                            obj[nodeName] = this.xmlToJson(item);
                        } else {
                            if (typeof(obj[nodeName].push) === "undefined") {
                                const old = obj[nodeName];
                                obj[nodeName] = [];
                                obj[nodeName].push(old);
                            }
                            obj[nodeName].push(this.xmlToJson(item));
                        }
                    }
                }
                return obj;
            },

            selected(item) {
                // XML转JSON格式使用
                // const xmlString = '<note><to>Tove</to><from>Jani</from></note>';
                // const parser = new DOMParser();
                // const xmlDoc = parser.parseFromString(xmlString, "text/xml");
                // const jsonObj = this.xmlToJson(xmlDoc);
                // console.log(jsonObj);
                console.log(item);
                if (item.status === 3) {
                    return
                } else {
                    updataEsim({
                        callback: this.getTimestamp(),
                        set_id: {
                            // simid: item.iccId
                            simid: Number(item.simId),
                            sn: this.snCode
                        }
                    }).then(res => {
                        const stringInfos = res.toString().substring(14); //删除前15位
                        const wifiValues = stringInfos.replace(`)`, ""); //删除")
                        const jsonDatas = this.$x2js.xml2js(wifiValues);
                        let isJson = JSON.parse(wifiValues.toString())
                        if (isJson.state == 1) {
                            this.$u.toast('切换成功,通常需要30秒以上能完成注网过程，请耐心等待!')
                            this.active = item.simId
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }



            },
            navTo(value) {
                if (!value) {
                    return
                }
                if (value == 'back') {
                    uni.navigateBack()
                    return
                }
                uni.navigateTo({
                    url: value
                });
            },
            deviceHandle(item) {
                console.log(item);
                if (item.id == '2') {
                    this.showModal = true;
                } else if (item.id == '1') {
                    this.show = true;
                } else if (item.id == '3') {
                    this.showModal2 = true;
                } else {
                    this.showModal1 = true;
                }
            },
            // 获取当前时间戳
            getTimestamp() {
                return new Date().getTime();
            },

            //恢复出厂设置
            confirm() {
                this.showModal = false
                resetDevice({
                    callback: this.getTimestamp(),
                    factory_reset: {
                        sn: this.snCode
                    }
                }).then(res => {
                    console.log("恢复出厂设置");
                    if (res.includes("1}")) {
                        this.bindStatus = false
                        this.$u.toast('恢复成功,通常需要30秒以上能完成注网过程，请耐心等待并重新连接!')
                    } else {
                        // this.bindStatus = false
                        this.$u.toast('当前用户连接的网络与设备的网络不一致,无法操作!')
                    }

                    // const stringInfos = res.toString().substring(15); //删除前15位
                    // const wifiValues = stringInfos.replace(`")`, ""); //删除")
                    // const jsonDatas = this.$x2js.xml2js(wifiValues);
                    // console.log(jsonDatas.blog.wifi5Gsta);
                    // if (jsonDatas.blog.wifi5Gsta) {
                    //     this.bindStatus = false
                    //     this.$u.toast('恢复成功,通常需要30秒以上能完成注网过程，请耐心等待并重新连接!')
                    // }

                }).catch(err => {
                    console.log(err)
                })
            },

            confirm1() {
                this.showModal1 = false
                this.$u.toast('暂无接口')
            },
            //重启
            confirm2() {
                this.showModal2 = false
                restartDevice({
                    callback: this.getTimestamp(),
                    reboot: {
                        sn: this.snCode
                    }

                }).then(res => {
                    // const stringInfos = res.toString().substring(15); //删除前15位
                    // const wifiValues = stringInfos.replace(`")`, ""); //删除")
                    // const jsonDatas = this.$x2js.xml2js(wifiValues);
                    // if (jsonDatas.blog.wifi5Gsta) {
                    //     this.bindStatus = false
                    //     this.$u.toast('重启成功,通常需要30秒以上能完成注网过程，请耐心等待并重新连接!')
                    // }
                    console.log("重启");
                    console.log(res);
                    if (res.includes("1}")) {
                        this.bindStatus = false
                        this.$u.toast('重启成功,通常需要30秒以上能完成注网过程，请耐心等待并重新连接!')
                    } else {
                        this.$u.toast('当前用户连接的网络与设备的网络不一致,无法操作!')
                    }



                }).catch(err => {
                    console.log(err)
                })
            },




            intoInfo() {
                getInfo({
                    callback: this.getTimestamp(),
                    act_mode: 0
                }).then((res) => {
                    //需要处理你的格式，不是标准的xml
                    // let stringInfo = res.toString().substring(15); //删除前15位
                    // let wifiValue = stringInfo.replace(`")`, ""); //删除")
                    // const parser = new DOMParser();
                    // const xmlDoc = parser.parseFromString(wifiValue, 'text/xml');

                    if (res.includes("(")) {
                        this.bindStatus = true
                        let stringInfo = res.toString().substring(15); //删除前15位
                        let wifiValue = stringInfo.replace(`")`, ""); //删除")
                        const jsonData = this.$x2js.xml2js(wifiValue)
                        this.wifiInfo = jsonData.blog
                        console.log(this.wifiInfo);
                    } else {
                        this.bindStatus = false
                    }

                }).catch(err => {
                    console.log(err)
                })
            },


            submit() {
                if (this.form.passWord.length > 7) {
                    if (this.form.passWord === this.form.againPassWord) {
                        this.show = false;
                        set24G({
                            callback: this.getTimestamp(),
                            '24g_wifi_info_set': {
                                "username": `${this.form.wifiName}-2.4G`,
                                "password": this.form.passWord,
                                "wifitype": 2,
                                "wifimode": 0,
                                "wifimodeaction": 1,
                                "wifihide": 0,
                                "wifichannel": "0",
                                "wifibandwidth": "20",
                                "maxcount": "8",
                                "sn": this.snCode
                            }
                        }).then(res => {
                            set5G({
                                callback: this.getTimestamp(),
                                '5g_wifi_info_set': {
                                    "username": `${this.form.wifiName}-5G`,
                                    "password": this.form.passWord,
                                    "wifitype": 2,
                                    "wifimode": 0,
                                    "wifimodeaction": 1,
                                    "wifihide": 0,
                                    "wifichannel": "0",
                                    "wifibandwidth": "80",
                                    "maxcount": "32",
                                    "sn": this.snCode
                                }
                            }).then(res => {
                                const stringInfos = res.toString().substring(14); //删除前15位
                                const wifiValues = stringInfos.replace(`)`, ""); //删除")
                                let isJson = JSON.parse(wifiValues.toString())
                                console.log("isJson" + isJson.state);
                                // const jsonDatas = this.$x2js.xml2js(wifiValues);
                                if (isJson.state == 1) {
                                    this.bindStatus = false
                                    this.$u.toast('设置成功,通常需要30秒以上能完成注网过程，请耐心等待并重新连接!')
                                }
                            }).catch(err => {
                                console.log(err)
                            })
                        }).catch(err => {
                            console.log(err)
                        })

                    } else {
                        this.$u.toast('请确认两次密码是否一致！')
                    }
                } else {
                    this.$u.toast('密码长度不能小余8位数！')
                }



            }
        }
    }
</script>

<style lang="scss">
    .eye {
        padding: 0 20rpx;

        .pass-icon {
            width: 36rpx;
            height: 36rpx;
        }
    }


    .body {
        font-size: 28rpx;

        .active {
            border: 1px solid #517af1 !important;
            color: #517af1 !important;
        }
    }

    .actionRight-icon {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #FFFFFF;

        .look {
            font-size: 28rpx;
            line-height: 1;
            margin-right: 12rpx;
            text-decoration: underline;
        }
    }

    .top_block {
        // padding-top: var(--status-bar-height);
        // padding-top: 60rpx !important;
        box-sizing: border-box;
        height: 300rpx;


        .navbar_wrap {
            width: 100%;
            color: #FFFFFF;

            .navbar {
                position: relative;
                display: flex;
                align-items: center;
                width: 100%;
                // height: 88rpx;


                .title {
                    flex: 1;
                    text-align: center;
                    font-size: 36rpx;
                    font-family: Source Han Sans CN;
                    font-weight: bold;
                    color: #FFFFFF;
                }

                .right {
                    flex-shrink: 0;
                    position: absolute;
                    right: 30rpx;

                    image {
                        width: 34rpx;
                        height: 40rpx;
                    }
                }

                .left {
                    position: absolute;

                    .arrow-right {
                        transform: rotate(180deg);
                        height: 34rpx;
                        padding-right: 20rpx;
                    }
                }
            }
        }

        .isAction {
            width: 100%;
            height: 160rpx;
            margin-top: 50rpx;
            display: flex;
            box-sizing: border-box;
            padding: 0 24rpx;

            .actionLeft,
            .actionRight {
                text-align: center;

                .img {
                    width: 70rpx;
                    height: 70rpx;
                }
            }

            .actionCenter {
                flex: 1;
                font-size: 28rpx;
                margin-left: 24rpx;
                color: #fff;
            }


        }



    }

    .wifiTitle {
        width: 96%;
        height: 100rpx;
        align-items: center;
        color: #999;
        margin-left: 2%;
        display: flex;
        justify-content: space-between;

    }

    .network,
    .device {
        width: 96%;
        margin-left: 2%;

        .title {
            font-size: 36rpx;
            font-weight: 600;
            color: #000;
        }

        .contain {
            width: 98%;
            margin-top: 30rpx;
            margin-left: 1%;

            .justDiv {
                border-radius: 20rpx;
                border: 3rpx solid #e7e7e7;
                width: 200rpx;
                height: 200rpx;
                color: #999;
                text-align: center;

                .img {
                    width: 80rpx;
                    height: 80rpx;
                }
            }

            .justDiv2 {
                border-radius: 20rpx;
                width: 160rpx;
                height: 170rpx;
                color: #333;
                text-align: center;

                .img {
                    width: 100rpx;
                    height: 100rpx;
                }
            }
        }
    }

    .device {}


    .form-box {
        box-sizing: border-box;
        padding: 32rpx 28rpx;

        .btn {
            margin-top: 24rpx;
            margin-bottom: 44rpx;
        }
    }
</style>